package api

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"seat-service/initialization"
	"seat-service/model"
	"seat-service/model/dto"
	"seat-service/response"
	service "seat-service/service/impl"
	"strconv"
)

var searchRecord service.SearchRecordService

type SearchRecordApi struct {
}

func (*SearchRecordApi) Delete(c *gin.Context) {
	par := c.Param("id")
	id, err := strconv.Atoi(par)
	if err != nil {
		resp.Fail(c, response.CodeParamError, nil)
		return
	}
	if err := searchRecord.Delete(id); err != nil {
		initialization.SeatLogger.Error(" searchRecord.Delete(id) failed", zap.Error(err))
		resp.Fail(c, response.CodeServerBusy, nil)
		return
	}
	resp.Success(c, response.CodeSuccess, nil)
}

func (*SearchRecordApi) Save(c *gin.Context) {
	par := model.SearchRecord{}
	if err := c.ShouldBind(&par); err != nil {
		initialization.SeatLogger.Error("c.ShouldBind(par) failed", zap.Error(err))
		resp.Fail(c, response.CodeParamError, nil)
		return
	}
	sid, _ := c.Get("id")
	par.StudentID = sid.(uint)
	// 获取记录
	if err := searchRecord.Get(&par); err != nil {
		if err == gorm.ErrRecordNotFound {
			searchRecord.Update(&par)
		} else {
			initialization.SeatLogger.Error("searchRecord.Get(&par); failed", zap.Error(err))
			resp.Fail(c, response.CodeServerBusy, nil)
			return
		}
	}
	if par.ID != 0 { // 已存在，更新
		searchRecord.Update(&par)
	} else { // 创建
		searchRecord.Save(&par)
	}
	if err := searchRecord.Save(&par); err != nil {
		initialization.SeatLogger.Error("searchRecord.Add(par) failed", zap.Error(err))
		resp.Fail(c, response.CodeServerBusy, nil)
		return
	}
	resp.Success(c, response.CodeSuccess, nil)
	return
}

// GetByPage 获取搜索记录
func (*SearchRecordApi) GetByPage(c *gin.Context) {
	page := &dto.PageParam{}
	if err := c.ShouldBind(page); err != nil {
		initialization.SeatLogger.Error("c.ShouldBind(page) failed", zap.Error(err))
		resp.Fail(c, response.CodeParamError, nil)
		return
	}
	id, _ := c.Get("id")
	page.Data = id.(uint)
	search, err := searchRecord.GetByPage(page)
	if err != nil {
		initialization.SeatLogger.Error("searchRecord.GetByPage(page) failed", zap.Error(err))
		resp.Fail(c, response.CodeServerBusy, nil)
		return
	}
	resp.Success(c, response.CodeSuccess, search)
	return
}
